package com.ljx.recruitment.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.recruitment.common.domain.vo.resp.PageResp;
import com.ljx.recruitment.common.enums.CommonStatusTypeEnum;
import com.ljx.recruitment.common.exception.ApiException;
import com.ljx.recruitment.security.util.UserUtil;
import com.ljx.recruitment.user.domain.entity.Menu;
import com.ljx.recruitment.user.domain.entity.Role;
import com.ljx.recruitment.user.domain.vo.req.RolePageReq;
import com.ljx.recruitment.user.domain.vo.req.RoleSubmitReq;
import com.ljx.recruitment.user.domain.vo.req.RoleToUserReq;
import com.ljx.recruitment.user.domain.vo.resp.MenuResp;
import com.ljx.recruitment.user.mapper.RoleMapper;
import com.ljx.recruitment.user.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-10-31  14:23
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Long> getUserRoleIdByUserId(Long userId) {
        return roleMapper.getUserRoleByUserId(userId);
    }

    @Override
    public List<Role> getRoleByIds(List<Long> roleIds) {
        return listByIds(roleIds);
    }

    @Override
    public void allocationToUser(RoleToUserReq req) {
        checkPermission(req);
        deleteUserRole(req.getUserId());
        for (Long roleId : req.getRoleIds()) {
            insertUserRole(req.getUserId(), roleId);
        }
    }

    @Override
    public List<Role> getRoleLikeName(String roleName) {
        return roleMapper.selectList(new LambdaQueryWrapper<Role>()
                .eq(Role::getStatus, CommonStatusTypeEnum.NORMAL.getKey())
                .like(Role::getName, roleName));
    }

    @Override
    public PageResp<Role> getPage(RolePageReq req) {
        LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(req.getKey())){
            lambdaQueryWrapper.like(Role::getName, req.getKey());
        }
        Page<Role> page = roleMapper.selectPage(new Page<>(req.getCurrPage(), req.getPageSize()), lambdaQueryWrapper);
        return PageResp.<Role>builder()
                .total(page.getTotal())
                .list(page.getRecords())
                .build();
    }

    @Override
    public Role submit(RoleSubmitReq req) {
        Role role;
        if (Objects.isNull(req.getId())){
            role = BeanUtil.copyProperties(req, Role.class);
            roleMapper.insert(role);
        } else {
            role = roleMapper.selectById(req.getId());
            BeanUtils.copyProperties(req, role);
            roleMapper.updateById(role);
        }

        return role;
    }

    private void checkPermission(RoleToUserReq req) {
        Long userTenantId = UserUtil.tryToGetUserTenantId(req.getUserId());
        Long tenantId = UserUtil.tryToGetTenantId();
        if (!tenantId.equals(userTenantId) && !UserUtil.checkIsPlatformAdmin()){
            throw new ApiException("权限不足");
        }
    }

    @Override
    public List<Long> getPermissions(Long roleId) {
        return roleMapper.getPermissions(roleId);
    }

    @Override
    public List<Long> getMenus(Long roleId) {
        return roleMapper.getMenus(roleId);
    }

    @Override
    public void saveRolePermissionsById(Long id, List<Long> permissionIds) {
        if (CollectionUtil.isEmpty(permissionIds)) {
            return;
        }
        roleMapper.saveRolePermissionsById(id, permissionIds);
    }

    @Override
    public void saveRoleMenusById(Long id, List<Long> menuIds) {
        if (CollectionUtil.isEmpty(menuIds)) {
            return;
        }
        roleMapper.saveRoleMenusById(id, menuIds);
    }


    @Override
    public Role getByName(String roleName) {
        if (StrUtil.isEmpty(roleName)) {
            throw new ApiException("角色不能不能为空");
        }
        return roleMapper.selectOne(new LambdaQueryWrapper<Role>()
                .eq(Role::getName, roleName)
                .eq(Role::getStatus, CommonStatusTypeEnum.NORMAL.getKey()));
    }

    @Override
    public void insertUserRole(Long userId, Long roleId) {
        if (Objects.isNull(userId)) {
            throw new ApiException("用户ID不能为空");
        }
        if (Objects.isNull(roleId)) {
            throw new ApiException("角色ID不能为空");
        }
        roleMapper.insertUserRole(userId, roleId);
    }

    @Override
    public void deleteUserRole(Long userId) {
        if (Objects.isNull(userId)) {
            throw new ApiException("用户ID不能为空");
        }
        roleMapper.deleteUserRole(userId);
    }
}
